package com.zy.user.controller;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.util.HttpSessionMutexListener;

import com.zy.user.pojo.User;
import com.zy.user.service.UserService;

@Controller
public class UserController{
	@Autowired
	private UserService userService;
	
	@RequestMapping("/login.do")
	@ResponseBody
	public User login( User user) {
		User u =userService.login(user);
		if(u !=null) {
			userService.updateTime(u);
		}
		return u;
	}
	
	@RequestMapping("/userList.do")
	@ResponseBody
	public List<User> selectAll() {
		List<User> list =userService.selectAll();
		return list;
	}
	
	@RequestMapping("/deleteById.do")
	@ResponseBody
	public boolean deleteUser(User user) {
		boolean result =userService.deleteUserById(user);
		return result;
	}
	
	@RequestMapping("/addUser.do")
	public String addUser(@RequestParam("img")MultipartFile f1, User user){

		String filename =f1.getOriginalFilename();
		File file =new File("C:\\Users\\zhang'yuan\\Desktop\\图片",filename);
		try {
			f1.transferTo(file);
		} catch (IllegalStateException e) {
			e.printStackTrace();
		}catch(IOException e){
			e.printStackTrace();
		}
		user.setUimage("images/"+filename);
		boolean result =userService.addUser(user);
				System.out.println("添加用户结果为：");
		return "userlist";
	}
	
	@RequestMapping("/updateUser.do")
	public String updateUser(@RequestParam("img")MultipartFile f1, User user){

		String filename =f1.getOriginalFilename();
		File file =new File("C:\\Users\\zhang'yuan\\Desktop\\图片",filename);
		try {
			f1.transferTo(file);
		} catch (IllegalStateException e) {
			e.printStackTrace();
		}catch(IOException e){
			e.printStackTrace();
		}
		user.setUimage("images/"+filename);
		boolean result =userService.updateUser(user);
				System.out.println("更新用户结果为：");
		return "userlist";
	}
	@RequestMapping("/updateUserPage.do")
	public String updatePage(User user, HttpSession session) {
		session.setAttribute("uid", user.getUid());
		System.out.println("数据为"+user.getUid());
		return "updateUser";
	}
	@RequestMapping("/selectUser.do")
	@ResponseBody
	public User selectUser(HttpSession session) {
		User u=(User) session.getAttribute("uid");
		User user =userService.selectUserById(u);
		return user;
	}
	@RequestMapping("/selectUserWithUsername.do")
	public List<User> selectUserWithUsername(User u){
		List<User> list =userService.selectUserWithUsername(u);
		return list;
		
	}
}








